package cz.muni.fi.pa165.pokemon.dao.impl;

import cz.muni.fi.pa165.pokemon.dao.PokemonDAO;
import cz.muni.fi.pa165.pokemon.entity.Pokemon;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Dusan Svancara
 */
@Repository
public class PokemonDAOImpl implements PokemonDAO {
    
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void create(Pokemon pokemon) {
        if (pokemon == null) {
            throw new IllegalArgumentException("pokemon is null");
        }
        if (pokemon.getId() != null) {
            throw new IllegalArgumentException("pokemon has non-null id");
        }
        entityManager.persist(pokemon);
    }

    @Override
    public Pokemon get(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("id is null");
        }
        return entityManager.find(Pokemon.class, id);
    }

    @Override
    public void update(Pokemon pokemon) {
        if (pokemon == null) {
            throw new IllegalArgumentException("pokemon is null");
        }
        if (pokemon.getId() == null) {
            throw new IllegalArgumentException("pokemon.id is null");
        }
        
        entityManager.merge(pokemon);
    }

    @Override
    public void remove(Pokemon pokemon) {
        if (pokemon == null) {
            throw new IllegalArgumentException("pokemon is null");
        }
        if (pokemon.getId() == null) {
            throw new IllegalArgumentException("pokemon.id is null");
        }
        Pokemon toRemove = entityManager.find(Pokemon.class, pokemon.getId());
        if (toRemove == null) {
            throw new IllegalArgumentException("given pokemon doesn't exist");
        }
        entityManager.remove(toRemove);
    }

    @Override
    public List<Pokemon> findAll() {
        TypedQuery<Pokemon> tq = entityManager.createQuery("FROM Pokemon", Pokemon.class);
        return tq.getResultList();
    }

    @Override
    public List<Pokemon> findByName(String name) {
        if (name == null) {
            throw new IllegalArgumentException("name is null");
        }
        TypedQuery<Pokemon> tq = entityManager.createQuery("SELECT s FROM Pokemon s WHERE s.name LIKE :name", Pokemon.class);
        tq.setParameter("name", name);

        return tq.getResultList();
    }
    
}
